package com.hahaliu.hahaliu.service.impl.video;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hahaliu.hahaliu.common.exception.BaseException;
import com.hahaliu.hahaliu.common.utils.RedisUtil;
import com.hahaliu.hahaliu.mapper.DanmuMapper;
import com.hahaliu.hahaliu.mapper.VideoMapper;
import com.hahaliu.hahaliu.pojo.entity.Danmu;
import com.hahaliu.hahaliu.pojo.entity.Video;
import com.hahaliu.hahaliu.service.video.DanmuService;
import com.hahaliu.hahaliu.service.video.VideoStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
* @author Liubuzhu
* @description 针对表【danmu】的数据库操作Service实现
* @createDate 2024-05-11 18:38:49
*/
@Service
public class DanmuServiceImpl extends ServiceImpl<DanmuMapper, Danmu>
    implements DanmuService{

	@Autowired
	private DanmuMapper danmuMapper;

	@Autowired
	private VideoMapper videoMapper;

	@Autowired
	private VideoStatsService videoStatsService;

	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 根据弹幕ID集合查询弹幕列表
	 * @param idset 弹幕ID集合
	 * @return  弹幕列表
	 */
	@Override
	public List<Danmu> getDanmuListByIdset(Set<Object> idset) {
		if (idset == null || idset.isEmpty()) {
			return null;
		}
		QueryWrapper<Danmu> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", idset).eq("state", 1);
		return danmuMapper.selectList(queryWrapper);
	}

	@Override
	@Transactional
	public void deleteDanmu(Integer id, Integer uid, boolean isAdmin) {
		QueryWrapper<Danmu> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id).ne("state", 3);
		Danmu danmu = danmuMapper.selectOne(queryWrapper);
		if (danmu == null) {
			throw new BaseException("弹幕不存在");
		}
		// 判断该用户是否有权限删除这条评论
		Video video = videoMapper.selectById(danmu.getVId());
		if (Objects.equals(danmu.getUId(), uid) || isAdmin || Objects.equals(video.getUId(), uid)) {
			// 删除弹幕
			UpdateWrapper<Danmu> updateWrapper = new UpdateWrapper<>();
			updateWrapper.eq("id", id).set("state", 3);
			danmuMapper.update(null, updateWrapper);
			videoStatsService.updateStats(danmu.getVId(), "danmu", false, 1);
			redisUtil.delMember("danmu_idset:" + danmu.getVId(), id);
		} else {
			throw new BaseException("你无权删除该条评论");
		}
	}
}




